<template>
  <div class="bgh">
    <!-- <div class="bgf">
      <!-- <div v-if="imagepath">
        <img :src="cardData.imagepath" width="100%" />
    </div>-->
    <!-- <div v-else style="height:200px;background:#fff" />

      <p class="fs16 infop">{{ cardData.itemname }}</p>
    </div>-->
    <div class="bgf" style="padding:10px 15px;">
      <p class="ggp fs16">
        规格
        <span style="float:right">
          价格：
          <span style="color:rgb(0, 178, 163)">￥{{chousedprice}}</span>
        </span>
      </p>
      <span
        v-for="(item, index) in pricetye"
        :key="index"
        :class="{activesex: checkActive(item)}"
        class="sexradio"
        @click="optionsClick(item)"
      >{{ item.specsname }}</span>

      <!-- {{ pricetye[1] }} -->
    </div>
    <div class="bgf infocontent">
      <p class="ggp fs16">商品详情</p>
      <div id="contentdiv">
        <!-- {{ cardData.context }} -->
      </div>
      <!-- <div v-for="(item, index) in lunbo" :key="index" style="margin-bottom:20px">
        <img :src="item" width="100%" />
      </div> -->
    </div>
    <!-- <div id="popover" class="box mui-popover mui-popover-action mui-popover-bottom">
      <div style="width:100%;height:150px;background:#fff;">
        <div>
          <img :src="imagepath" alt class="tc-img" />
          <span class="tc-guige">
            <span>{{ cardData.itemname }} （当前库存{{chousedprice2}}）</span>

            <br />
            <span style="display:inline-block;padding-right:50px;">规格:{{currValArr2[0]}}</span>
            <span class="fs16 colc">￥{{chousedprice}}</span>
          </span>
          <div
            style="padding:10px 20px 0px 40px;border-top:1px solid #aaa;display:flex;justify-content:space-between;align-items:center"
          >
            购买数量：
            <div class="mui-numbox" data-numbox-min="0" data-numbox-max="3">
              <!-- "-"按钮，点击可减小当前数值 
              <button class="mui-btn mui-numbox-btn-minus" type="button">-</button>
              <input v-model="tcnumber" class="mui-numbox-input" type="number" />
              <!-- "+"按钮，点击可增大当前数值 
              <button class="mui-btn mui-numbox-btn-plus" type="button">+</button>
            </div>
          </div>
          <button
            id="alertBtn"
            type="button"
            style="width: 100%;position: absolute;bottom: 0px;background:rgb(0, 178, 163);border:none"
            class="mui-btn mui-btn-primary"
            @click="gonuxt"
          >下一步</button>
        </div>
      </div>
    </div>-->

    <button
      v-if="$route.query.type=='1'"
      type="button"
      style="background:#00B2A3;color:#fff"
      class="mui-btn bottombtn"
      @click="dopay"
    >立即购买</button>

    <a
      v-else
      id="openPopover"
      href="#popover"
      style="background:#00B2A3;color:#fff"
      class="mui-btn bottombtn"
      @click="getcar"
    >加入购物车</a>
  </div>
</template>

<script>
export default {
  layout: 'default2',
  data() {
    return {
      ts: this.newStore(),
      pricetye: [],
      imagepath: '',
      lunbo: [],
      cardData: {},
      currValArr: [],
      currValArr2: [],
      tcnumber: 1,
      chousedprice: '',
      chousedprice2: ''
    }
  },
  created() {
    this.getcarddetail()
  },
  mounted() {
    mui('.mui-numbox').numbox()
  },
  methods: {
    //添加爱购物车
    getcar() {
      const res = {
        token: localStorage.getItem('token'),
        specsid: this.pricetye[0].specsid
      }
      this.spost(this.ts, '/Carc/addCar', res).then(ts => {
        if (ts.d.flag == '200') {
          mui.toast('添加成功！')
        } else {
          mui.toast(ts.d.message)
        }
      })
    },
    //增加量
    addkucun() {
      let chousnumber = mui('.mui-numbox')
        .numbox()
        .getValue()
      console.log(Number(this.tcnumber))
      console.log(Number(this.chousedprice2))
      if (Number(chousnumber) > Number(this.chousedprice2)) {
        mui.toast('库存不足', { duration: '500', type: 'div' })
        return
      }
    },
    //下一步
    gonuxt() {
      let chousnumber = mui('.mui-numbox')
        .numbox()
        .getValue()
      console.log(chousnumber, 'sss')
      const res = {
        token: localStorage.getItem('token'),
        specsid: this.currValArr[0],
        specssum: chousnumber
      }
      this.spost(this.ts, '/Carc/addCar', res).then(ts => {
        if (ts.d.flag == '200') {
          console.log(ts.d.data, '0001')
          //  var info = document.getElementById("info");
          document
            .getElementById('alertBtn')
            .addEventListener('tap', function() {
              mui.alert('成功加入购物车', '提示')
            })
        } else {
          document
            .getElementById('alertBtn')
            .addEventListener('tap', function() {
              mui.alert(ts.d.message, '提示')
            })
        }
      })
    },
    dopay() {
      const req = {
        token: localStorage.getItem('token')
      }
      this.spost(this.ts, '/Orderc/getOrderToken', req).then(ts => {
        const res = {
          token: localStorage.getItem('token'),
          specsid: this.currValArr[0],
          ordertoken: ts.d.data.ordertoken,
          orderno: ts.d.data.orderno
        }
        this.spost(this.ts, 'Orderc/orderAdd', res).then(ts2 => {
          this.prepayid = ts2.d.data
          this.PayMoney()
          // console.log(ts2.d.message)
          // mui.alert(ts2.d.message, '提示', () => {
          //   this.$router.push('/fmine')
          // })
        })
      })
    },
    //立即支付调用微信接口，生产环境使用
    PayMoney() {
      if (typeof WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            this.onBridgeReady,
            false
          )
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
        }
      } else {
        this.onBridgeReady()
      }
    },
    onBridgeReady() {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          timeStamp: `${this.prepayid.timeStamp}`, // 时间戳，自1970年以来的秒数
          appId: `${this.prepayid.appId}`, // 公众号名称，由商户传入
          nonceStr: `${this.prepayid.nonceStr}`, // 随机串
          package: `${this.prepayid.package}`, //
          signType: `${this.prepayid.signType}`, // 微信签名方式
          paySign: `${this.prepayid.paySign}` // 微信签名
        },
        res => {
          // alert(JSON.stringify(res))
          // alert(`输入密码后从微信服务器返回来的支付结果：${JSON.stringify(res)}`);
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            console.log('res.err_msg', res.err_msg)
            mui.alert('支付成功', '提示', () => {
              this.$router.push({
                name: 'ddpage',
                query:{
                  from:'我的',
                  word:'我的服务'
                }
              })
            })
            // mui.alert('支付成功', '提示')
            // this.$router.push({
            //   name: 'chufang-payOff',
            //   query: {
            //     je_sf: this.je_sf,
            //     payResult: true,
            //     payMessage: '支付成功'
            //   }
            // })
          } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            // this.$router.push({ name: 'payOff', query: { je_sf: this.je_sf, payResult: false, payMessage: '取消支付' } });
            // this.showAlert = true
            // this.alertText = '已取消支付'
            //  mui.alert('已取消支付', '提示')
            console.log('res.err_msg', res.err_msg)
          } else {
            // this.$router.push({ name: 'payOff', query: { je_sf: this.je_sf, payResult: false, payMessage: res.err_msg } });
            // this.showAlert = true
            // this.alertText = `支付失败,错误信息${res.err_msg}`
            // mui.alert(`支付失败,错误信息${res.err_msg}`, '提示')
            console.log('res.err_msg', res.err_msg)
          }
        }
      )
    },
    checkActive(item) {
      // this.chousedprice=item.price
      // console.log(item,'0000');
      // this.chousedprice=item.price
      return this.currValArr.indexOf(item.specsid) !== -1
    },
    optionsClick(item) {
      console.log(item, '22')
      this.chousedprice = item.price
      this.chousedprice2 = item.num
      this.$set(this.currValArr, 0, item.specsid)
      this.$set(this.currValArr2, 0, item.specsname)
      console.log(this.currValArr2[0], '6666')
    },
    getcarddetail() {
      this.pricetye = []
      this.currValArr = []
      this.lunbo = []
      this.imagepath = ''
      this.cardData = {}
      const req = {
        itemno: this.$route.query.cardid
      }
      this.spost(this.ts, '/itemc/getbyitemno', req).then(ts => {
        this.pricetye = ts.d.data
        console.log(this.pricetye[0].price)
        if (this.pricetye.length != 0) {
          this.chousedprice2 = this.pricetye[0].num
          this.currValArr.push(this.pricetye[0].specsid)
          this.currValArr2.push(this.pricetye[0].specsname)
          this.chousedprice = this.pricetye[0].price
        }
      })
      this.spost(this.ts, '/itemc/getitembyid', req).then(ts2 => {
        let dom = document.getElementById('contentdiv')
        this.cardData = ts2.d.data
        dom.innerHTML = this.cardData.context

        if (this.cardData.itemlunbo.length != 0) {
          this.lunbo = this.cardData.itemlunbo
          this.imagepath = this.lunbo[0]
        }
      })
    }
  }
}
</script>

<style>
.ggp {
  height: 30px;
  line-height: 30px;
  color: #333;
}
.infop {
  line-height: 20px;
  padding: 15px;
  margin-bottom: 6px;
}
.sexradio {
  background: #b5b5b5;
  display: inline-block;
  padding: 6px 12px;
  margin: 0 6px 0px 0px;
  border-radius: 15px;
  color: #fff;
}
.activesex {
  background: #00b2a3;
}
.infocontent {
  padding: 10px 15px;
  margin: 5px 0;
  margin-bottom: 50px;
}
.bottombtn {
  position: fixed;
  padding: 10px;
  width: 90%;
  bottom: 2%;
  left: 5%;
  border-radius: 25px;
  border: 0;
}
#contentdiv img {
  width: 100%;
  height: auto;
}
.tc-img {
  width: 80px;
  height: auto;
  position: absolute;
  top: -25px;
  left: 30px;
  border-radius: 8px;
  padding: 2px;
  border: 1px solid #ccc;
  background: #fff;
}
.tc-guige {
  display: block;
  padding-left: 125px;
  padding-top: 10px;
  line-height: 25px;
}
</style>
